package com.logistics.controller;

import com.logistics.conf.Constants;
import com.logistics.entity.User;
import com.logistics.service.UserService;
import com.logistics.util.JsonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Ranger on 2015/8/17.
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Resource
    UserService userService;

    /**
     * <p>客户登录</p>
     * <p>GET  /user/login</p>
     *
     * @param user 需要进行登录的用户
     * @throws IOException 返回JSON数据给前端时可能会抛出这个异常
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public void login(User user, Model model, HttpSession session, HttpServletResponse response) throws IOException {
        User userRec = userService.login(user);
        if (userRec != null) {
            model.addAttribute("user", user);
            session.setAttribute(Constants.USER_UID, user.getEmail());
            JsonUtil.writeMsg(String.valueOf(userRec.getId()), response);
        } else {
            JsonUtil.writeMsg("-1", response);
        }
    }

    /**
     * <p>用户注册</p>
     * <p>GET  /user/register</p>
     *
     * @param user 要进行注册的用户
     * @throws IOException 返回JSON数据给前端时可能会抛出这个异常
     */
    @RequestMapping(value = "register", method = RequestMethod.POST)
    public void register(User user, Model model, HttpSession session, HttpServletResponse response) throws IOException {
        User userRec = userService.register(user);
        if (userRec != null) {
            model.addAttribute("user", user);
            session.setAttribute(Constants.USER_UID, user.getEmail());
            JsonUtil.writeMsg(String.valueOf(userRec.getId()), response);
        } else {
            JsonUtil.writeMsg("-1", response);
        }
    }

    /**
     * <p>用户注销</p>
     * <p>GET    /user/logout</p>
     *
     * @param user 需要注销的用户
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public void logout(User user, HttpSession session) {
        session.removeAttribute("user");
    }

    /**
     * <p>更新用户信息</p>
     * <p>PUT    /user</p>
     *
     * @param user 更改信息之后的用户对象
     */
    @RequestMapping(method = RequestMethod.PUT)
    public void alter(User user) {
        userService.update(user);
    }

    /**
     * <p>删除用户</p>
     * <p>DELETE    /user</p>
     *
     * @param idArray 需要删除的用户的ID数组
     */
    @RequestMapping(method = RequestMethod.DELETE)
    public void delete(int[] idArray) {
        for (int id : idArray) {
            userService.delete(id);
        }
    }
}
